package exp03.tracker.dao;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;
import exp03.tracker.models.Region;

import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lg_en
 */
@Repository
public class CoronaVirusData implements InitializingBean {
    /*
    * 数据源url
    * */
    private static final String CORONA_VIRUS_DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private final List<Region> allRegionStats = new ArrayList<>();

    public List<Region> getAllRegionStats() {return allRegionStats;}

    /*
    * 每天凌晨1点执行计划任务，更新allRegionStats.
    * allRegionStats成员变量储存着全球新型冠状病毒统计数据
    *
    * Throws:IDException - IO异常
    * */
    @Scheduled(cron = "${lg.Schedules.updateVirusDataCron}")
    public void fetchCoronaVirusData() throws IOException{

        //爬取全球新型冠状病毒统计数据的csv文件
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> responseEntity = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource resource = responseEntity.getBody();

        //通过Resource对象的getInputStream方法获取csv文件的输入流
        Reader in = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
//        InputStream inputStream = resource.getInputStream();
//        InputStreamReader reader = new InputStreamReader(inputStream);
//        Reader in = new BufferedReader(reader);

        Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
//      Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);

        boolean isHeader = true;

        //保存每天的日期
        List<String> dateList = new ArrayList<>();
        int id = 0;
        for(CSVRecord record : records){
            //第一行为日期
            if(isHeader){
                isHeader = false;
                //第一行前四列不是日期
                for(int i = record.size()-1;i>=4;i--){
                    String[] split = record.get(i).split("/");
                    dateList.add("20"+split[2]+"年"+split[0]+"月"+split[1]+"日");
                }
            }
            else{
                //获取数据
                Region region = new Region();
                Map<String,Long> map = new LinkedHashMap<>();

                //前四列不是病例
                for (int i = record.size()-1,j=0;i>=4;i--,j++){
                    map.put(dateList.get(j),Long.valueOf(record.get(i)));
                    }

                //编号
                region.setId(++id);
                //州或省
                region.setState(record.get(0));
                //国家或地区
                region.setCountry(record.get(1));
                //最新病例数
                region.setLatestTotalCases(Integer.parseInt(record.get(record.size()-1)));
                //新增病例数
                int different = Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2));
                region.setDiffFromPrevDay(different);
                //每天病例数据
                region.setData(map);
                //添加到list
                allRegionStats.add(region);
            }
        }
    }

    /*
    * 实现Bean的声明回调函数
    * */
    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }

}
